<template>
	<!-- 返回顶部按钮 -->
	<div class="scrollTop" v-show="showTop" @click="toTop"></div>
</template>
<script>
export default {
	name: 'scroll-top',
	data() {
		return {
			scrollTop: 0,
			time: 0,
			dParams: 20,
			scrollState: 0
		};
	},
	computed: {
		showTop() {
			return this.scrollTop > 200;
		}
	},
	mounted() {
		window.addEventListener('scroll', this.getScrollTop);
	},
	methods: {
		toTop(e) {
			if (!!this.scrollState) {
				return;
			}
			this.scrollState = 1;
			e.preventDefault();
			let distance = document.documentElement.scrollTop || document.body.scrollTop;
			let _this = this;
			this.time = setInterval(function() {
				_this.gotoTop(_this.scrollTop - _this.dParams);
			}, 50);
		},
		gotoTop(distance) {
			this.dParams += 20;
			distance = distance > 0 ? distance : 0;
			document.documentElement.scrollTop = document.body.scrollTop = window.pageYOffset = distance;
			if (this.scrollTop < 10) {
				clearInterval(this.time);
				this.dParams = 20;
				this.scrollState = 0;
			}
		},
		getScrollTop() {
			this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
		}
	}
};
</script>
<style scoped>
.scrollTop {
	width: 62px;
	height: 62px;
	position: fixed;
	right: 20px;
	bottom: 80px;
	cursor: pointer;
	background: url('../../../assets/images/top1.png') no-repeat;
}
.scrollTop:hover {
	background: url('../../../assets/images/top2.png') no-repeat;
}
</style>
